package com.snail.snailvr.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.player.PlayActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class Util {

    public static int VersionCode = -1;

    public static int getSelfVersionCode() {
        if (VersionCode <= 0) {
            Context context = VRApp.getInstance();
            PackageInfo info = PackageInfoUtil.getPackageInfoByName(context, context.getPackageName());
            if (info != null)
                VersionCode = info.versionCode;
        }

        return VersionCode;
    }


    public static String getDuration(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        return formatter.format(time);
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName;
        try {
            versionName = context.getPackageManager().getPackageInfo(Constant.PACKAGE_NAME, 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versionName = "1.0";
        }
        return versionName;
    }

    public static String getVideoPathFromUri(Uri uri, Activity activity) {
        String value = uri.getPath();

        if (value.startsWith("/external")) {
            String[] proj = {MediaStore.Video.Media.DATA};
            Cursor cursor = activity.managedQuery(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            cursor.close();
            return path;
        } else {
            return value;
        }
    }

    /**
     * 检查Intent 是否在 系统存在
     */
    public static boolean isIntentSafe(Context context, Intent targetIntent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(targetIntent, 0);
        return activities.size() > 0;
    }

    public static void showMarket(Activity activity) {
        final String appPackageName = Constant.PACKAGE_NAME;
        try {
            Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage("com.android.vending");
            // package name and activity
            ComponentName comp = new ComponentName("com.android.vending", "com.google.android.finsky.activities.LaunchUrlHandlerActivity");
            launchIntent.setComponent(comp);
            launchIntent.setData(Uri.parse("market://details?id=" + appPackageName));

            activity.startActivity(launchIntent);

        } catch (Exception exception) {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    }

    public static int getNavigationModeResId(int navigationMode) {
        if (PlayActivity.SNVR_NAVIGATION_SENSOR == navigationMode) {
            return R.drawable.ic_player_normal;
        } else if (PlayActivity.SNVR_NAVIGATION_TOUCH == navigationMode) {
            return R.drawable.ic_player_move;
        } else {
            return R.drawable.ic_player_normal;
        }

    }

    public static int getPlayModelResId(int mProjectionType) {
        if (PlayActivity.SNVR_PROJ_PLANE == mProjectionType) {
            return R.drawable.ic_player_plane;
        } else if (PlayActivity.SNVR_PROJ_SPHERE == mProjectionType) {
            return R.drawable.ic_player_sphere;
        } else {
            return R.drawable.ic_player_dome;
        }

    }

    public static int getSpliceFormatResId(int videoSpliceFormat) {

        if (PlayActivity.SNVR_VIDEO_SPLICE_FMT_2D == videoSpliceFormat) {
            return R.drawable.ic_player_2d;
        } else if (PlayActivity.SNVR_VIDEO_SPLICE_FMT_3D_SBS == videoSpliceFormat) {
            return R.drawable.ic_player_3d_side;
        } else {
            return R.drawable.ic_player_3d_under;
        }
    }

    public static boolean isHttpUrl(String videoPath) {
        return !TextUtils.isEmpty(videoPath) && videoPath.startsWith("http");
    }

    public static boolean isLiveUrl(String videoPath) {
        return !TextUtils.isEmpty(videoPath) && (videoPath.startsWith("rtmp://") || videoPath.endsWith(".m3u8")|| videoPath.endsWith(".flv"));
    }

    public static Paint getDividerPaint() {
        Paint paint = new Paint();
        paint.setColor(VRApp.getInstance().getResources().getColor(R.color.common_divider_color));
        paint.setStrokeWidth(1);
        return paint;
    }

    // 开始旋转动画
    public static void startRotateAnimation(View view, RotateAnimation rotate) {
        rotate = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(750);
        rotate.setInterpolator(new DecelerateInterpolator());
        rotate.setRepeatCount(-1);
        view.startAnimation(rotate);
    }

    // 停止旋转动画
    public static void stopRotateAnimation(RotateAnimation rotate) {
        if (rotate != null) {
            rotate.cancel();
            rotate.reset();
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context,float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public static int getStatesBarHeight() {
        int i = VRApp.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
        int j = 0;
        if (i > 0)
            j = VRApp.getContext().getResources().getDimensionPixelSize(i);
        return j;
    }

    public static void setDrawableLeft(TextView title, int resId) {
        Drawable drawable = VRApp.getContext().getResources().getDrawable(resId);
        setDrawableLeft(title, drawable);
    }


    public static void setDrawableLeft(TextView title, Drawable drawable) {

        if (drawable == null)
            return;
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        title.setCompoundDrawables(drawable, null, null, null);
    }

    public static void setDrawableTop(TextView title, int resId) {
        Drawable drawable = VRApp.getContext().getResources().getDrawable(resId);
        setDrawableTop(title, drawable);
    }

    public static void setDrawableTop(TextView title, Drawable drawable) {

        if (drawable == null)
            return;
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        title.setCompoundDrawables(null, drawable, null, null);
    }

    /**
     * 拼接字符串
     *
     * @return
     */
    public static String getRepeatFileName(String source, int fix) {
        int index = source.lastIndexOf(".");
        String target = source.substring(0, index) +
                "-" +
                fix +
                source.substring(index);

        return target;
    }

    /**
     * 取得IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        return imei;
    }

    /**
     * Android获取手机的型号
     */
    public static String getPhoneType() {
        try {
            return URLEncoder.encode(android.os.Build.MODEL, "UTF-8");// 获取手机型号
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    public static String getCurrentLanguage() {

        Locale locale = VRApp.getInstance().getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh")) {
            if (locale.getCountry().equals("CN")) {
                return "zh_CN";
            } else {
                return "zh_TW";
            }

        } else if (language.endsWith("en"))
            return "en_US";

        return "zh_CN";
    }
}
